﻿namespace UnityEditor
{
    using System;
    using System.Runtime.InteropServices;

    public class VCMonitor : AssetModificationProcessor
    {
        public static bool IsOpenForEdit(string assetPath, out string message)
        {
            message = string.Empty;
            if (!VCProvider.enabled)
            {
                return true;
            }
            if (string.IsNullOrEmpty(assetPath))
            {
                return true;
            }
            VCAsset assetByPath = VCDatabase.GetAssetByPath(assetPath);
            if (assetByPath == null)
            {
                VCTask task = VCProvider.StatusAbsolutePath(assetPath);
                task.Wait();
                assetByPath = (task.assetList.Count <= 0) ? null : task.assetList[0];
            }
            if (assetByPath == null)
            {
                return false;
            }
            return VCProvider.IsOpenForEdit(assetByPath);
        }

        private static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions option)
        {
            if (!VCProvider.enabled)
            {
                return AssetDeleteResult.DidNotDelete;
            }
            VCTask task = VCProvider.Delete(assetPath);
            task.Wait();
            VCDatabase.InvalidateAtProjectPath(assetPath);
            return (!task.success ? AssetDeleteResult.FailedDelete : AssetDeleteResult.DidNotDelete);
        }

        private static AssetMoveResult OnWillMoveAsset(string from, string to)
        {
            if (!VCProvider.enabled)
            {
                return AssetMoveResult.DidNotMove;
            }
            VCTask task = VCProvider.Move(from, to);
            task.Wait();
            VCDatabase.InvalidateAtProjectPath(from);
            VCDatabase.InvalidateAtProjectPath(to);
            return (!task.success ? AssetMoveResult.FailedMove : ((AssetMoveResult) task.resultCode));
        }
    }
}

